HackerRank Two Characters
提出
3/32
code: python
import math
import os
import random
import re
import sys
import string
import itertools
from copy import *
#
# Complete the 'alternate' function below.
#
# The function is expected to return an INTEGER.
# The function accepts STRING s as parameter.
#
def alternate(s):
# Write your code here
ascii_low = string.ascii_lowercase
strings = []
for i in range(25):
if (s.find(ascii_lowi) != -1): strings.append(ascii_lowi) ans = -1
for i in itertools.permutations(strings, 2):
res = 0
idx = 0
s_copy = list(deepcopy(s))
while(s_copy):
next = s_copy.pop(0)
if (idx == 0):
res += 1
idx = 1
if (idx == 1):
res += 1
idx = 0
if (res > ans):
ans = res
return ans
if __name__ == '__main__':
l = int(input().strip())
s = input()
result = alternate(s)
fptr.write(str(result) + '\n')
fptr.close()
解答
code: python
import math
import os
import random
import re
import sys
#
# Complete the 'alternate' function below.
#
# The function is expected to return an INTEGER.
# The function accepts STRING s as parameter.
#
def alternate(s):
# Write your code here
maxnum = count = 0
alp = list(set(s)) # produces unique char
# find all combinations of char
for i in range(len(alp)):
for j in range(i+1, len(alp)):
# checks which char comes first in the string
if s.index(alpi) < s.index(alpj): idx = 0
else:
idx = 1
# check for alternate char and increment count
for char in s:
if char in l:
count += 1
# flip the index
idx = idx ^ 1
else:
# ex) a->b->b
count = 0
break
maxnum = max(maxnum, count)
count = 0
return maxnum
if __name__ == '__main__':
l = int(input().strip())
s = input()
result = alternate(s)
fptr.write(str(result) + '\n')
fptr.close()
メモ
https://www.youtube.com/watch?v=YOtBCgFxnU0
提出
3/33 test cases failed :(
code: python
import math
import os
import random
import re
import sys
import collections
import itertools
#
# Complete the 'alternate' function below.
#
# The function is expected to return an INTEGER.
# The function accepts STRING s as parameter.
#
def alternate(s):
# Write your code here
c = collections.Counter(list(s))
ans = 0
for v1, v2 in itertools.combinations(c.keys(), 2):
res = []
for i in range(len(s)):
if len(res) > 1 and res-1 == si: res.clear()
break
else:
if len(res) > ans:
ans = len(res)
return ans
if __name__ == '__main__':
l = int(input().strip())
s = input()
result = alternate(s)
fptr.write(str(result) + '\n')
fptr.close()